<template>
	<view class="certif-form">
		<gyd-navbar back-color="#fff" :title="title"></gyd-navbar>

		<u-form class="form" labelPosition="left" :model="formData" :rules="rules" :ref="formRef">
			<u-form-item class="form-item" label="资质名称" labelWidth="100" prop="name">
				<u-input v-model="formData.name" placeholder="请输入资质名称"></u-input>
			</u-form-item>
			<u-form-item class="form-item" label="资质类型" labelWidth="100" prop="type">
				<u-radio-group v-model="formData.type" @change="changeCerType">
					<u-radio v-for="(item, index) in certificate_types" :key="index" :label="item.name"
						:name="item.value"></u-radio>
				</u-radio-group>
			</u-form-item>

			<view class="upload-row">
				<view class="tips">资质图片（最多5张）</view>
				<uni-file-picker v-model="imageLists" return-type="array" file-mediatype="image" mode="grid"
					:image-styles="imageStyles" :file-extname="extname" :auto-upload="false" custom-btn :limit="5"
					@select="selectFile($event)" @delete="removeOk($event)">
					<view class="custom-upload" slot="addBtn">
						<uni-icons type="camera-filled" size="52" color="#999"></uni-icons>
					</view>
				</uni-file-picker>
			</view>

			<view class="form-item">
				<text class="label">资质有效期</text>
				<view class="value validity">
					<view class="left" v-if="!checked">
						<uni-datetime-picker type="date" :clear-icon="false" v-model="formData.certificate_expiry"
							@change="changeCertExpiry" />
					</view>
					<view class="right">
						<radio :value="formData.certificate_validity_type" :checked="checked"
							@click="changeValidityType">长期有效</radio>
					</view>
				</view>
			</view>
		</u-form>

		<view class="footer">
			<view class="btn-group">
				<u-button class="btn" type="primary" size="large" block @click="saveInfo()">提交</u-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import util from '@/utils/util';
	import {
		ref,
		reactive,
		toRefs,
		inject,
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReady,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';

	const state = reactive({
		title: '新增资质',
		themeColor: cache.get('themeColor'),
		imgHost: util.requestUrl(),
		certif_id: 0,
		formData: {
			id: 0,
			store_id: 0,
			shop_type: 0,
			name: '',
			type: 0,
			certificate_file: '',
			certificate_expiry: '',
			certificate_validity_type: '0',
			remark: '',
		},
		checked: false,
	});

	const rules = ref([]);
	const formRef = ref();
	const imageLists = ref([]);
	const extname = ref('jpg,jpeg,png,bmp,gif,tif,svg,webp');
	const imageStyles = ref({
		"width": '220rpx', // 边框宽度
		"height": '200rpx', // 边框高度
		"border": { // 如果为 Boolean 值，可以控制边框显示与否
			"color": "#909193", // 边框颜色
			"width": "1px", // 边框宽度
			"style": "solid", // 边框样式
		}
	});
	const certificate_types = ref([]);

	//在页面所有元素加载完成后执行（只执行一次）
	onLoad((opt) => {
		console.log('onLoad');
		let selStore = cache.get('selStore');
		console.log('店铺信息', selStore);
		if (selStore) {
			state.formData.store_id = selStore.id;
			state.formData.shop_type = selStore.user_type;
		}
		if (opt.hasOwnProperty('id')) {
			console.log('传递参数', opt.id);
			state.certif_id = opt.id;
			state.title = '更新资质';
			getDetail();
		}
		getCertificateType();
	});

	//在页面由不可见变为可见时执行（只要页面显示都会执行）
	onShow(() => {
		console.log('onShow');
	})

	//在页面解析完成之后执行
	onReady(() => {
		console.log('onReady');
	})

	onPullDownRefresh(() => {
		console.log('下拉刷新');
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
	})

	onReachBottom(() => {
		console.log('触底加载更多');
	})

	function getDetail() {
		request.get('store.credential/detail', {
			id: state.certif_id
		}).then(res => {
			console.log('资质详情', res);
			state.formData = res.data;
			state.formData.certificate_validity_type = res.data.certificate_validity_type + '';

			let certificate_files = res.data.certificate_files;
			certificate_files.forEach(item => {
				imageLists.value.push({
					name: item,
					extname: 'image',
					url: util.requestUrl() + item,
				});
			});
			console.log('资质详情-111', imageLists.value);

			if (state.formData.certificate_validity_type == '1') {
				state.checked = true;
			} else {
				state.checked = false;
			}
		})
	}

	function getCertificateType() {
		request.get('store.credential/getCertificateType', {}).then(res => {
			console.log('资质类型', res);
			certificate_types.value = res.data;
		})
	}

	function saveInfo() {
		let check = checkData();
		console.log('验证表单', check);
		if (!check) {
			return;
		}
		state.formData.certificate_file = '';
		imageLists.value.forEach((item, index) => {
			if (index == 0) {
				state.formData.certificate_file = item.name;
			} else {
				state.formData.certificate_file += ',' + item.name;
			}
		});
		console.log('表单验证通过，提交', state.formData);
		if (state.formData.id) {
			uni.showModal({
				title: '提示',
				content: '更新资质文件后需要平台重新审核，请谨慎操作！',
				success: function(res) {
					if (res.confirm) {
						console.log('用户点击确定');
						submit();
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			})
		} else {
			submit();
		}
	}

	function submit() {
		request.get('store.credential/save', state.formData).then(res => {
			console.log('保存资质', res);
			util.showTip('资质' + res.msg);

			setTimeout(() => {
				uni.navigateTo({
					url: '/merchantPages/store-manage/store-certif'
				})
			}, 1000)
		})
	}

	function checkData() {
		if (state.formData.store_id == 0 || state.formData.shop_type == 0) {
			util.showTip('店铺信息异常');
			return false;
		}
		if (!util.username(state.formData.name, '资质名称')) {
			return false;
		}
		if (state.formData.type == 0) {
			util.showTip('请选择资质类型');
			return false;
		}
		if (imageLists.value.length == 0) {
			util.showTip('请上传资质文件');
			return false;
		}
		if (!state.checked) {
			if (!state.formData.certificate_expiry) {
				util.showTip('请选择资质有效期');
				return false;
			}
		}

		return true;
	}

	function changeCerType(e) {
		console.log('选择资质类型', e);
	}

	function changeCertExpiry(e) {
		console.log('是否长期', e);
		state.checked = false;
	}

	function changeValidityType(e) {
		state.checked = !state.checked;
		console.log('checked', state.checked);
		if (state.checked) {
			state.formData.certificate_validity_type = '1';
		} else {
			state.formData.certificate_validity_type = '0';
		}
	}

	// 选择图片
	function selectFile(res) {
		console.log('selectFile', res);

		// 上传
		for (let i = 0; i < res.tempFilePaths.length; i++) {
			upload(res.tempFilePaths[i]);
		}
	}

	// 删除照片
	function removeOk(res) {
		console.log('removeOk', res);
		// imageLists.value = [];//单图
		imageLists.value.splice(res.index, 1); //多图
	}

	// 图片上传
	function upload(file) {
		let type = "credential";
		uni.uploadFile({
			url: util.requestUrl() + '/api/upload/uploadfile', // 开发者服务器接口地址
			filePath: file, // 要上传文件资源的路径
			name: 'file', // 文件对应的 key
			formData: {
				'type': type,
				'token': cache.get('M_LOGIN_TOKEN', false) || '',
				'role': cache.get('role', false) || 0,
			}, // 请求的 form data
			success: (res) => {
				const json = JSON.parse(res.data);
				if (json.code == 1) {
					const data = json.data;
					console.log('上传成功', data);
					util.showTip(data.originalName + '上传成功');
					// 处理上传成功的结果
					imageLists.value.push({
						name: data.url,
						extname: data.fileType,
						url: data.url2,
					});
				}
			},
			fail: (error) => {
				console.error('上传失败', error);
				// 处理上传失败的错误
				uni.showToast({
					title: '网络错误，请稍后再试！',
					icon: fail,
					duration: 2000
				})
			}
		});
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	}

	function pageTabRoute(url) {
		uni.reLaunch({
			url
		});
	}

	const {
		title,
		themeColor,
		imgHost,
		certif_id,
		formData,
		checked,
	} = toRefs(state);
</script>

<style lang="scss">
	.certif-form {
		padding-bottom: calc(100rpx + env(safe-area-inset-bottom));

		.form {
			padding: $m24;

			.form-item {
				background: #fff;
				margin-bottom: $m16;
				padding: 0 $m24;
				border-radius: 10rpx;

				.label {
					width: 140rpx;
					color: $main-color;
				}

				.value {
					flex: 1;
					padding: 10rpx 0;
					color: $main-color;
				}

				.validity {
					display: flex;

					.left {
						flex: 1;
					}

					.right {
						margin-left: 30rpx;
						width: 200rpx;
					}
				}
			}

			.upload-row {
				padding: 0 0 $m24 $m24;
				margin-top: $m12;

				.tips {
					margin-bottom: $m12;
					color: $tips-color;
				}
			}
		}

		.footer {
			position: fixed;
			/* 固定在底部 */
			bottom: 0;
			width: 100%;

			.btn-group {
				.btn {}
			}
		}
	}
</style>